"""
使用方法：
C:\Windows\system32>F:
F:\>cd F:\code\python\test
F:\code\python\test>
"""


import subprocess
import os
import time
from pynput.keyboard import Key, Controller
import pyautogui
from datetime import datetime, timedelta
import tkinter as tk
import threading


#mouse = Controller()
keyboard = Controller()
# 创建一个停止事件
stop_event = threading.Event()
images_path = "d:\\"
global musouProcess
musou_thread = None
global offset_second
global exclude_times
finishtimes = '''00:18:45
00:19:25
00:20:05
00:21:55
00:22:35
00:23:09
00:24:59
00:25:39
00:26:19
00:28:49
00:52:45
00:53:25
00:54:05
00:55:55
00:56:35
00:57:09
01:00:10
01:02:40
01:03:20
01:04:00
01:05:50
01:06:24
01:07:04
01:08:54
01:09:34
01:25:06
01:32:56
01:33:30
01:34:10
01:36:40
01:37:20
01:38:00
01:39:50
01:40:24
01:41:04
02:07:41
02:08:15
02:16:45
02:17:25
02:18:05
02:19:55
02:20:35
02:21:09
02:22:59
02:41:41
02:42:21
02:43:01
02:44:51
02:45:25
02:46:05
03:00:40
03:01:20
03:02:00
03:03:50
03:15:46
03:22:26
03:23:06
03:24:56
03:25:36
03:26:16
03:28:40
03:56:26
03:57:06
07:05:38
07:06:12
07:08:42
07:09:22
07:10:02
07:41:43
07:42:23
07:43:03
07:44:53
07:45:33
07:46:07
07:47:57
07:54:37
07:55:17
07:57:41
11:37:02
11:38:46
11:39:26
11:40:06
11:41:56
12:03:58
12:04:28
12:05:18
12:07:48
12:08:22
12:09:02
12:10:52
12:19:31
12:20:11'''

def adjust_time_list(time_list):
    new_time_list = []
    for time_str in time_list:
        hour, minute, second = map(int, time_str.split(':'))
        if 16 <= minute <= 21 or 32 <= minute <= 37 or 48 <= minute <= 53:
            minute -= 6
        if 16 <= second <= 21 or 32 <= second <= 37 or 48 <= second <= 53:
            second -= 6
        new_time_list.append(f"{hour:02d}:{minute:02d}:{second:02d}")
    return new_time_list

def convert_time_list(time_list):
    time_list = time_list.strip().split('\n')
    time_list = [time.strip() for time in time_list if time.strip()]
    new_list = adjust_time_list(time_list)
    return new_list

def thread_sleep(n):
    if stop_event.is_set():
        print_message("游戏已经结束了，你个老6，你可以重新开始了")
        stop_event.clear()
        exit(0)
    time.sleep(n)

def get_timestring():
    current_time = datetime.now()

    # 将时间格式化为HHMMSS形式的字符串
    time_string = current_time.strftime("%H%M%S")

    return time_string

def press_hold_time(key, sec):
    keyboard.press(key)
    thread_sleep(sec)
    keyboard.release(key)

def send(key):
    keyboard.press(key)
    thread_sleep(0.1)
    keyboard.release(key)
    thread_sleep(0.1)

def skip_start():
    # 此处仍然有3-5秒播放，是为了确保准确率。系统不一定每次都是一样的速度启动游戏。系统快可以设置低，慢的话可以设置为25，或者更大
    thread_sleep(20)
    print_message("跳过开头动画")
    send(Key.enter)
    thread_sleep(3)

def press_any_key():
    # 进入主菜单，等待时间为6秒
    print_message("按任意键进入主菜单")
    send(Key.enter)
    thread_sleep(5)

def select_free_mode():
    send(Key.up)
    print_message("选择自由模式")
    thread_sleep(1)
    send(Key.enter)
    print_message("进入自由模式")
    thread_sleep(5)

def select_level():
    select_free_mode()

    #选择战役
    print_message("选择千里走单骑")
    send(Key.right)
    thread_sleep(1)
    send(Key.down)
    thread_sleep(1)
    send(Key.down)
    thread_sleep(1)
    send(Key.down)
    thread_sleep(1)
    send(Key.down)
    thread_sleep(1)
    send(Key.enter)
    thread_sleep(3)

    #选择难度
    print_message("选择入门")
    send(Key.enter)
    thread_sleep(2)
    send(Key.left)
    thread_sleep(1)
    send(Key.left)
    thread_sleep(1)
    send(Key.enter)
    thread_sleep(5)

    #选择武将，按5次->，选择赵云，每一次Key.right都会向右移动一次，选择下一个武将
    print_message("选择赵云")

    #send(Key.right)
    #thread_sleep(1)
    #send(Key.right)
    #thread_sleep(1)
    #send(Key.right)
    #thread_sleep(1)
    #send(Key.right)
    #thread_sleep(1)
    #send(Key.right)
    #thread_sleep(1)
    send(Key.enter)
    thread_sleep(5)

def prepare():
    # 战斗准备
    print_message("战斗准备")
    send(Key.enter)
    thread_sleep(2)
    send(Key.up)
    thread_sleep(2)
    send(Key.enter)
    thread_sleep(2)

    # 选择护卫
    print_message("选择护卫")
    send(Key.enter)
    thread_sleep(2)

    # 返回
    send(Key.esc)
    thread_sleep(2)
    send(Key.esc)
    thread_sleep(2)

def start_game():
    # 开始战斗
    send(Key.up)
    thread_sleep(2)
    print_message("开始战斗")
    send(Key.enter)

    thread_sleep(5)
    send(Key.esc)
    print_message("跳过开场动画")
    thread_sleep(2)


def create_images_path():
    global images_path
    current_dir = os.getcwd()
    # 创建保存路径
    images_path = os.path.join(current_dir, 'images')

    # 创建images文件夹
    os.makedirs(images_path, exist_ok=True)
    print_message("武器截图目录：" + images_path)

def save_weapon_image(name):
    global images_path
    screenshot = pyautogui.screenshot(region=(500, 200, 1200, 600))
    print_message("武器截图：" + images_path + "\\" + name)
    screenshot.save(images_path + "\\" + name)

def musou(timestr):
    global musouProcess
    global images_path
    imagename = timestr.replace(':', '') + '.jpg'
    # app1 = subprocess.Popen("D:\Program Files\\Notepad--\\Notepad--.exe")
    # app = Application().start("D:\\娱乐\\真三国无双4S\\musou.exe")
    # app = Application().start("D:\Program Files\\Notepad--\\Notepad--.exe")
    set_system_time(timestr)
    exe_dir = os.path.dirname(images_path)
    os.chdir(exe_dir)
    musouProcess = subprocess.Popen(exe_dir + "\\musou.exe")

    # 完全打开
    skip_start()

    #===press any key
    press_any_key()

    #选择战役
    select_level()

    #战斗准备
    prepare()

    start_game()

    #调整到防御
    #send(Key.enter)
    #thread_sleep(1)
    thread_sleep(4)
    if offset_second > 1:
        print_message("低配配置电脑")
        thread_sleep(3)

    print_message("正前方视角")
    send('l')
    thread_sleep(1)

    print_message("走1.6秒")
    press_hold_time('w', 1.6)
    thread_sleep(1.5)

    print_message("右转")
    send('d')
    thread_sleep(1.5)

    print_message("正前方视角")
    send('l')
    thread_sleep(1)

    print_message("走18秒")
    press_hold_time('w', 18)

    #thread_sleep(1.5)
    #send('d')
    #print_message("右转")
    #thread_sleep(1.5)
    #send('l')
    #print_message("正前方视角")
    #thread_sleep(1.5)
    #press_hold_time('w', 4)
    #print_message("走4秒")

    thread_sleep(15)
    for i in range(10):
        send('j')
        thread_sleep(1)
        send('m')
        thread_sleep(1)

    print_message("战斗胜利")
    thread_sleep(26)
    print_message("确认功勋")
    send(Key.enter) # 功勋确认
    thread_sleep(5)
    print_message("确认级别")
    send(Key.enter) # 级别
    thread_sleep(5)

    #武器情况
    print_message("武器截图保存")
    save_weapon_image(imagename)
    thread_sleep(2)
    send(Key.enter)
    thread_sleep(2)
    musouProcess.terminate()
    thread_sleep(4)

def set_system_time(timestr):
    os.system('time ' + timestr)

def exist_in(time_string, time_array):
    # 遍历时间列表中的每个时间字符串
    for t in time_array:
        # 判断当前时间字符串的前 5 个字符（小时和分钟）是否与时间列表中的对应部分匹配
        if t.startswith(time_string[:5]):
            return True
    return False

def run(startpoint, endpoint):
    create_images_path()
    time_array = convert_time_list(exclude_times)
    # 将输入的时间字符串转换为 datetime 格式
    start_time = datetime.strptime(startpoint, "%H:%M:%S")
    end_time = datetime.strptime(endpoint, "%H:%M:%S")

    # 设置起始时间为当天的午夜 00:00:00
    current_date = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
    start_time = current_date.replace(hour=start_time.hour, minute=start_time.minute, second=start_time.second)
    print_message("起始时间：" + start_time.strftime("%H:%M:%S"))

    # 设置结束时间为当天的午夜 23:59:59
    end_time = current_date.replace(hour=end_time.hour, minute=end_time.minute, second=end_time.second)
    print_message("结束时间：" + end_time.strftime("%H:%M:%S"))
    print_message("三国无双启动速度：" + str(offset_second))

    # 遍历所有秒数，并打印为时间
    current_time = start_time
    while current_time <= end_time and not stop_event.is_set():
        if (current_time.minute < 16 or current_time.minute > 21) and \
                (current_time.minute < 32 or current_time.minute > 37) and \
                (current_time.minute < 48 or current_time.minute > 53) and \
                (current_time.second < 16 or current_time.second > 21 - offset_second) and \
                (current_time.second < 32 or current_time.second > 37 - offset_second) and \
                (current_time.second < 48 or current_time.second > 53 - offset_second):
            timestr = current_time.strftime("%H:%M:%S")
            print_message(timestr)
            if 60 - offset_second > current_time.second and exist_in(timestr, time_array):
                print_message(timestr + "这一分钟已经刷完，跳过")
                # 从本minute的第59秒开始，继续
                current_time = current_time.replace(second=60 - offset_second)
                continue
            musou(timestr)
        current_time += timedelta(seconds=1)
        if stop_event.is_set():
            stop_event.clear()
            break

def run_script():
    global musou_thread
    global offset_second
    global exclude_times
    if musou_thread is not None and musou_thread.is_alive():
        # 将之前的线程设置为守护线程
        musou_thread.daemon = True
        musou_thread = None
    start_time = start_entry.get()
    end_time = end_entry.get()
    offset_second = int(offset_entry.get())
    exclude_times = exclude_time_box.get("1.0", tk.END)
    musou_thread = threading.Thread(target=run, args=(start_time, end_time))
    musou_thread.start()

def stop_script():
    global musou_thread
    musouProcess.terminate()
    stop_event.set()
    if musou_thread:
        musou_thread.join(timeout=2)
        if musou_thread.is_alive():
            musou_thread._delete()
    print_message('需要等待, 提示”游戏已经结束了，你个老6, 你可以重新开始了“之后，才能再次开始')

def print_message(msg):
    text_box.insert(tk.END, msg + '\n')
    text_box.see(tk.END)

root = tk.Tk()
root.title('Musou刷武器')
root.geometry('400x500')


# 创建标签和输入框组件
start_time_container = tk.Frame(root)
start_time_container.pack(side=tk.TOP)
start_label = tk.Label(start_time_container, text='起始时间（hh:mm:ss）')
start_label.pack(side=tk.LEFT)

start_entry = tk.Entry(start_time_container)
start_entry.insert(0, '08:00:00')
start_entry.pack(side=tk.LEFT)

end_time_container = tk.Frame(root)
end_time_container.pack(side=tk.TOP)
end_label = tk.Label(end_time_container, text='结束时间（hh:mm:ss）')
end_label.pack(side=tk.LEFT)

end_entry = tk.Entry(end_time_container)
end_entry.insert(0, '08:00:01')
end_entry.pack(side=tk.LEFT)


# 创建标签和输入框组件
exclude_time_container = tk.Frame(root)
exclude_time_container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

exclude_time_label = tk.Label(exclude_time_container, text="排除时间点：")
exclude_time_label.pack(side=tk.LEFT, fill=tk.X)

# 创建滚动信息栏
exclude_time_scrollbar = tk.Scrollbar(exclude_time_container)
exclude_time_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 创建文本框
exclude_time_box = tk.Text(exclude_time_container, yscrollcommand=exclude_time_scrollbar.set, height=10, width=40)
exclude_time_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
exclude_time_box.insert(tk.END, finishtimes)

# 将滚动信息栏关联到文本框
exclude_time_scrollbar.config(command=exclude_time_box.yview)


# 创建运行按钮组件
# 创建容器
button_container = tk.Frame(root)
button_container.pack(side=tk.TOP)

offset_label = tk.Label(button_container, text='无双程序启动速度(秒)')
offset_label.pack(side=tk.LEFT)

offset_entry = tk.Entry(button_container, width=10)
offset_entry.insert(0, '1')
offset_entry.pack(side=tk.LEFT)


run_button = tk.Button(button_container, text='开始', command=run_script)
run_button.pack(side=tk.LEFT)

# 创建结束按钮组件
stop_button = tk.Button(button_container, text='结束', command=stop_script)
stop_button.pack(side=tk.LEFT)


# 创建容器
text_box_container = tk.Frame(root)
text_box_container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

# 创建滚动信息栏
scrollbar = tk.Scrollbar(text_box_container)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# 创建文本框
text_box = tk.Text(text_box_container, yscrollcommand=scrollbar.set, height=10, width=50)
text_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# 将滚动信息栏关联到文本框
scrollbar.config(command=text_box.yview)

root.mainloop()
